<?php
/**
 * 咨询师
 *
 * User: kaikaic
 * Date: 2018/12/6
 * Time: 20:43
 */

namespace app\api\controller;

use app\admin\service\CityService;
use app\admin\service\TagsService;
use app\psy\service\ConsultantExtendService;
use app\psy\service\ConsultantService;
use app\psy\service\OrderService;
use controller\BasicApi;
use think\Db;

class Consult extends BasicApi {

    public function index() {
        //TODO
        $size = 5;
        $page = intval($this->request->param("page",1));
        $city = intval($this->request->param("areaid",0));
        $priceid = intval($this->request->param("priceid",0));
        $pricestart = trim($this->request->param("pricestart"));
        $priceend = trim($this->request->param("priceend"));
        $goodatarea = trim($this->request->param("goodatarea",0));
        $name= trim($this->request->param("name",''));
        $type2 = trim($this->request->param("type",0));
        $start = ($page-1)*$size;
        $db =  Db::name('psy_consultant');
        $db = $db->where('status',2) ;
        if($name){
            $db =   $db->whereLike('name',"%".$name."%") ;
        }
        if($city){
            $db =   $db->where('city_id',$city) ;
        }
        if($priceid){
//            $condition['price'] = array('between',"$pricestart,$priceend");
            $db = $db->whereBetween('price',"$pricestart,$priceend");
        }

        $limit = "$start,$size";
        $records =$db->limit($limit)->select();
        foreach ($records as $key =>&$item){
            $goodatArr = unserialize($item['goodat_ids']);
            $type = unserialize($item['type_ids']);
            if($goodatarea){
                $goodatid = explode(",",$goodatarea);
                $res = array_intersect($goodatid,$goodatArr);
                if(empty($res)){
                    unset($records[$key]);
                }
            }
            if($type2){
                $typeid = explode(",",$type2);
                $res2 = array_intersect($typeid,$type);
                if(empty($res2)){
                    unset($records[$key]);
                }
            }


            $city = CityService::getInstance()->single(array('area_id'=>$item['city_id']));
            $item['city'] = $city['area_name'];
            // 资质
            $tagsList = TagsService::getInstance()->getTagsArrayByAbbr("psy_qualification");
            if ($item['qualification']) {
                $item['qualification'] = $tagsList[$item['qualification']];
            }else {
                $item['qualification'] = "";
            }
            $item['qualification'] = $item['qualificationtext'];
            $consultType = $this->readCategoryConfig("psy_consult");

            $typeStr = "";
            foreach ($type as $key) {
                $typeStr .= $consultType[$key] . "/";
            }
            $item['type_txt'] = trim($typeStr, "/");
        }
        $this->success('获取成功',$records);
    }
    public function getoption(){
        $res['func'] = $this->readCategoryConfig("psy_consult");
        $res['tagsList'] = TagsService::getInstance()->getTagsArrayByAbbr("tags_type");
        $res['area'] = CityService::getInstance()->select(array('area_parent_id'=>0));
        $this->outputJsonSuccess('获取成功',$res);
    }
    public function getarealist(){
        $province = intval($this->request->param("province",0));
        $area = CityService::getInstance()->select(array('area_parent_id'=>$province));
        $this->outputJsonSuccess('获取成功',$area);
    }
    public function getprovincelist(){
        $area = CityService::getInstance()->select(array('area_deep'=>1));
        $this->outputJsonSuccess('获取成功',$area);
    }
    /**
     * 咨询师详情
     */
    public function view() {
        $id = intval($this->request->param("id"));
        $account_id = intval($this->request->param("account_id",0));
        // 是否是咨询师
        $record = ConsultantService::getInstance()->single(array('id'=>$id));

        if (!$record) {
            $this->outputJsonError("没有这个咨询师");
        }

        // '1'=>'待审核', '2'=>'已通过', '3'=>'已拒绝', '4'=>'已禁用'
        if ($record['status'] != 2) {
            $this->outputJsonError("没有这个咨询师", 401);
        }
        $record['isfollow'] = 0;
        if($account_id){
            $res = Db::name('psy_follow')
                -> where('account_id',$account_id)
                ->where('type','consult')
                ->where('target_id',$id)->select();
            if($res){
                $record['isfollow'] = 1;
            }
        }
        $dataArray = array();
        // 咨询师基本信息
        $dataArray['basic'] = $this->consultantBasic($record);
        //工作时段
        $dataArray['hour'] = $this->consultantHour($record);
        // 咨询师相册
        $dataArray['photos'] = $this->consultantPhoto($id);
        // 咨询师培训
        $dataArray['train'] = $this->consultantTrain($id);
        // 咨询师教育经历
        $dataArray['education'] = $this->consultantEducation($id);
        $this->success('获取成功',$dataArray);
    }
    public function view1() {
        $id = intval($this->request->param("id"));
        $record = ConsultantService::getInstance()->single(array('id'=>$id));
        if (!$record) {
            $this->outputJsonError("没有这个咨询师");
        }

        $dataArray = array();
        // 咨询师相册
        $dataArray['photos'] = $this->consultantPhoto($id);
        // 咨询师培训
        $dataArray['train'] = $this->consultantTrain($id);
        // 咨询师教育经历
        $dataArray['education'] = $this->consultantEducation($id);
        //咨询师个案咨询经历
        $dataArray['pexp'] = $this->consultantPexp($id);
        //咨询师督导经历
        $dataArray['supexp'] = $this->consultantSupexp($id);
        $this->success('获取成功',$dataArray);
    }
    private function consultantPhoto($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->selectlimit($where, 2);

        $photos = array();
        for ($i=0; $i<count($records); $i++) {
            $photos[] = $records[$i]['photo'];
        }

        return $photos;
    }

    private function consultantTrain($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where, 1);

        $trains = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();

            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['intro'] = $records[$i]['intro'] ."\n导师：".$records[$i]['leader'].",培训主题：".$records[$i]['theme']." 培训时长:".$records[$i]['hours'];
            $temp['hours'] = $records[$i]['hours'];
            $temp['id'] = $records[$i]['id'];
            $temp['theme'] = $records[$i]['theme'];
            $temp['leader'] = $records[$i]['leader'];
            $temp['photos'] = explode(',',$records[$i]['photos']);
            $trains[] = $temp;
        }

        return $trains;
    }

    private function consultantEducation($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where);

        $educations = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();

            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['school'] = $records[$i]['school'];
            $temp['major'] = $records[$i]['major'];
            $temp['education'] = $records[$i]['education'];
            $temp['id'] = $records[$i]['id'];
            $temp['photos'] = explode(',',$records[$i]['photos']);
            $educations[] = $temp;
        }

        return $educations;
    }
    private function consultantPexp($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where, 5);
        $pexps = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();
            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['intro'] = $records[$i]['intro'];
            $temp['hours'] = $records[$i]['hours'];
            $temp['leading'] = $records[$i]['leading'];
            $temp['leadphone'] = $records[$i]['leadphone'];
            $temp['leadname'] = $records[$i]['leadname'];
            $temp['id'] = $records[$i]['id'];
            $temp['photos'] = explode(',',$records[$i]['photos']);
            $pexps[] = $temp;
        }
        return $pexps;
    }
    private function consultantSupexp($id) {
        $where = array();
        $where['consultant_id'] = $id;
        $records = ConsultantExtendService::getInstance()->select($where, 6);

        $supexps = array();
        for ($i=0; $i<count($records); $i++) {
            $temp = array();

            $s = date("Y-m", strtotime($records[$i]['start_date']));
            $e = date("Y-m", strtotime($records[$i]['end_date']));
            $temp['date'] = $s . "至" . $e;
            $temp['start_date'] = $records[$i]['start_date'];
            $temp['end_date'] = $records[$i]['end_date'];
            $temp['intro'] = $records[$i]['intro'];
            $temp['hours'] = $records[$i]['hours'];
            $temp['supname'] = $records[$i]['supname'];
            $temp['forwards'] = $records[$i]['forwards'];
            $temp['id'] = $records[$i]['id'];
            $temp['photos'] = explode(',',$records[$i]['photos']);
            $supexps[] = $temp;
        }

        return $supexps;
    }
    private function consultantBasic($basic) {
        $city = CityService::getInstance()->single(array('area_id'=>$basic['city_id']));
        $basic['city'] = $city['area_name'];
        // 资质
        $tagsList = TagsService::getInstance()->getTagsArrayByAbbr("psy_qualification");
        if ($basic['qualification']) {
            $basic['qualification'] = $tagsList[$basic['qualification']];
        }else {
            $basic['qualification'] = "";
        }
        $basic['qualification'] = $basic['qualificationtext'];
        $consultType = $this->readCategoryConfig("psy_consult");
        $type = unserialize($basic['type_ids']);
        $typeArr = array();
        $typeStr = "";
        $i = 0;
        foreach ($type as $key) {
            $typeStr .= $consultType[$key] . "/";
            $typeArr[$i]['id'] = $key;

            $typeArr[$i]['name'] = $consultType[$key];
            $i++;
        }
        $basic['type_txt'] = trim($typeStr, "/");
        $basic['type'] = $typeArr;
        $factionsType = TagsService::getInstance()->getTagsArrayByAbbr("tags_factions");

        $factionids = unserialize($basic['factions_ids']);
        $typeStr = "";
        foreach ($factionids as $key) {
            $typeStr[$key] = $factionsType[$key];
        }
        $basic['factionsType'] = $typeStr;

        $tags_type = TagsService::getInstance()->getTagsArrayByAbbr("tags_type");

        $goodat_ids = unserialize($basic['goodat_ids']);
        $goodatStr = "";
        foreach ($goodat_ids as $key) {
            $goodatStr[$key] = $tags_type[$key];
        }
        $basic['goodatType'] = $goodatStr;
        $basic['peroidType'] = unserialize($basic['period_ids']);
        return $basic;
    }
    private function consultantHour($basic) {
        $condition['consultant_id'] = $basic['id'];
        $workorder =Db::query("select concat(order_time,' ', order_periods) as truename from psy_order where consultant_id=".$basic['id']);

        $workorder = array_column($workorder , 'truename' );
        $time = time();
        $peroidType = unserialize($basic['period_ids']);
        $week = $this->getWeekday($time);
        $first = $week[0];
        /**
         * 138	工作日上午	27	1541258484
        139	工作日下午	27	1541258493
        140	工作日晚上	27	1541258503
        141	周末上午	27	1541258514
        142	周末下午	27	1541258523
        143	周末晚上	27	1541258534
         */
        if($peroidType){
            $monthDate = array();
            for ($i=0; $i<30; $i++) {
                $day = $weekDate[$i]['day'] = date("Y-m-d", strtotime("+{$i} day", strtotime($first)));
                $weekDate[$i]['d'] = date("d", strtotime("+{$i} day", strtotime($first)));
                $weekDate[$i]['m'] = date("m", strtotime("+{$i} day", strtotime($first)));
                $weekDate[$i]['now'] = date("Y-m-d",time());
                $week = date('w', strtotime("+{$i} day", strtotime($first)));
                $workday = array('1','2','3','4','5');
                $weekday = array('0','6');
                $timer = array();
                $dateArray = array();
                if(in_array('138',$peroidType)){
                    $worktime = array(9, 10, 11);
                    if(in_array($week,$workday)){

                        $timer =   array_merge($timer,$worktime);

                    }
                }
                if(in_array('139',$peroidType)){
                    $worktime = array(14, 15, 16, 17);
                    if(in_array($week,$workday)){

                        $timer =   array_merge($timer,$worktime);

                    }
                }
                if(in_array('140',$peroidType)){
                    $worktime = array(19, 20, 21);
                    if(in_array($week,$workday)){

                        $timer =   array_merge($timer,$worktime);

                    }
                }
                if(in_array('141',$peroidType)){
                    $worktime = array(9, 10, 11);
                    if(in_array($week,$weekday)){
                        $timer =   array_merge($timer,$worktime);
                    }
                }
                if(in_array('142',$peroidType)){
                    $worktime = array(14, 15, 16, 17);

                    if(in_array($week,$weekday)){
                        $timer = array_merge($timer,$worktime);
                    }
                }
                if(in_array('143',$peroidType)){
                    $worktime = array(19, 20, 21);
                    if(in_array($week,$weekday)){
                        $timer =   array_merge($timer,$worktime);
                    }
                }
                foreach ( $timer as $value=>$item) {
                    $day = date("Y-m-d", strtotime("+{$i} day", strtotime($first)));
                    $start =  date('H:i',(strtotime( $day) + $item * 3600));
                    $end =  date('H:i',(strtotime( $day) + $item * 3600+50*60));
                    $contact = $day.' '.$start.'-'.$end;
                    if(in_array($contact,$workorder)){

                    }else {
                        $dateArray[$value]['start'] =$start;
                        $dateArray[$value]['end'] =$end;
                        $dateArray[$value]['day'] = $day;
                        $dateArray[$value]['w'] = $this->weekday(strtotime("+{$i} day", strtotime($first)));
                    }
                }
                $weekDate[$i]['timer'] = $dateArray;
            }
            return $weekDate;
        }else{
            return array();
        }


        // 上午：9点，10点，11点



    }
    private function getWeekday($time) {
        $time = empty($time) ? time() : $time;

        $w = date('w', $time);
        $w = $w ?  $w : 7;

        $month = date('m', $time);
        $day = date('d', $time);
        $year = date('Y', $time);

        $data[] = date('Y-m-d', mktime(0, 0, 0, $month, $day - $w , $year));
        $data[] = date('Y-m-d', mktime(0, 0, 0, $month, $day + 7 - $w, $year));

        return $data;
    }
    private function weekday($time)
    {
        if(is_numeric($time))
        {
            $weekday = array('星期日','星期一','星期二','星期三','星期四','星期五','星期六');
            return $weekday[date('w', $time)];
        }
        return false;
    }
}

